<?php
namespace Common\Model;
use Think\Model;

class  CategoryModel extends  Model{
	private $table = 'category'; //指定表名
	/**
	 * 获得所有的栏目
	 */
	public function getAllData(){
		 $data = $this->field('category_id,cate_title,cate_sort,cate_time,state,cid')->select();
		 return $data;
		 
//		 $all =  $this->getSonData($data,0);
//		 return $all;
	}
	
//	/**
//	 * 获得所有的栏目
//	 */
//	private function getSonData($data,$id){
//		$tempArr = array();
//		foreach($data as $v){
//			if($v['cid'] == $id){
//				$tempArr[] = $v; 
//				$tempArr = array_merge($tempArr,$this->getSonData($data,$v['category_id']));
//			}
//		}		
//		return $tempArr;
//	}

	
	/**
	 * 添加栏目
	 */
	public function addData(){
		$postData = I('post.','','htmlspecialchars');
		$data = array(
			'cate_title' => $postData['cate_title'],
			'cate_sort' => $postData['cate_sort'],
			'cate_time' => date('Y-m-d H:i:s',time()),
			'state' => 'closed'
		);
		$row = $this->data($data)->add();
		return $row;
	}
	
	/**
	 * 添加子栏目
	 */
	public function addSonData(){
		$postData = I('post.');
		//先把父级变为closed
		$this->where(array('category_id'=>$postData['id']))->save(array('state'=>'closed'));
		//添加
		$data = array(
			'cate_title' => $postData['cate_title'],
			'cate_sort' => $postData['cate_sort'],
			'cate_time' => date('Y-m-d H:i:s',time()),
			'state' => 'open',
			'cid' => $postData['id']
		);
		$row = $this->data($data)->add();
		return $row;
	}
	
	/**
	 * 删除栏目
	 */
	public function delData(){
		$id = I('post.id');
		//先查询下是顶级栏目还是子栏目
		$data = $this->field('category_id')->where(array('cid'=>$id))->find();
		if($data){
			$rows = 0 ;
		}else{
			$rows = $this->where(array('category_id'=>$id))->delete();
		}
		return $rows;
	}
	
	/**
	 * 获得一条数据
	 */	
	public function getOneData($id){
		$data = $this->field('category_id,cate_title,cate_sort,cate_time,state,cid')->where(array('category_id'=>$id))->find();
		return $data;
	}
	/**
	 * 编辑数据
	 */
	public function editData($id){
		$postData = I('post.');
		$data = array(
			'cate_title'=>$postData['cate_title'],
			'cate_sort' => $postData['cate_sort']
		);
		$data = $this->where(array('category_id'=>$id))->save($data);
		return $data;
	}
	
	
}